package org.isifaces.component.tooltips;

import java.io.IOException;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.primefaces.component.tooltip.Tooltip;
import org.primefaces.renderkit.CoreRenderer;

public class TooltipsRenderer extends CoreRenderer {
	
	@Override
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		Tooltips tooltip = (Tooltips) component;

		for (UIComponent c : tooltip.getParent().getChildren())
			render(context, c);
	}

	private void render(FacesContext context, UIComponent comp) throws IOException {  
		if (comp.getChildCount() > 0) {
			// Traitement des enfants du composant
			for (UIComponent child : comp.getChildren())
				render(context, child);
		} else {
			UIComponent tooltip = new Tooltip(); // Creation d'un tooltip

			if (comp.getAttributes().get("title") != null) {
				Map<String, Object> attributes = tooltip.getAttributes();

				// On veut obtenir :
				// <p:tooltip for="slide" value="Title display" showEffect="slide" hideEffect="fade" />
				attributes.put("for", comp.getClientId(context));
				attributes.put("value", comp.getAttributes().get("title"));
				attributes.put("showEffect", "slide");
				attributes.put("hideEffect", "slide");

				comp.getParent().getChildren().add(tooltip);
			}
		}
	}

	@Override
	public void encodeChildren(FacesContext context, UIComponent component) throws IOException { }

	@Override
	public boolean getRendersChildren() {
		return true;
	}
}